//
//  ONUAddressLocationViewController.m
//  OneNineteen
//
//  Created by Mac on 2019/2/18.
//  Copyright © 2019 stoneobs.qq.com. All rights reserved.
//

#import "OELocationViewController.h"
#import <BaiduMapAPI_Utils/BMKFavPoiManager.h>
#import "OEAddressNearViewController.h"
@interface OELocationViewController ()
<UITextFieldDelegate,
BMKMapViewDelegate,
BMKSuggestionSearchDelegate,
BMKLocationManagerDelegate,
BMKLocationAuthDelegate>
@property(nonatomic, strong) NSMutableArray                     *dataSouce;/**<  */
@property(nonatomic, strong) STButton                          *addButton;/**< <##> */
@property(nonatomic, strong) UITextField                     *searchTextFied;/**< <##> */
@property(nonatomic, strong) BMKMapView                        *mapView;
@property(nonatomic, strong) BMKSuggestionSearch                     *searchManger;/**< 搜索 */
@property(nonatomic, strong) NSString                     *currentSarchName;/**< 当前搜索地址  */
@property(nonatomic, strong) BMKUserLocation                     *userLocation;/**< <##> */
@property(nonatomic, strong) NSString                     *cityName;/**<  */
@property(nonatomic, strong) NSString                     *ipx;/**<  */
@property(nonatomic, strong) NSString                     *ipy;/**<  */

@property(nonatomic, strong) BMKLocationManager                     *locationManager;/**< <##> */
@end

@implementation OELocationViewController
- (void)dealloc{
    DDLogInfo(@"ONUAddressLocationViewController  dealloc");
    _mapView.delegate = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Selcted Address";
    BMKSuggestionSearch *search = [[BMKSuggestionSearch alloc] init];
    search.delegate = self;
    self.searchManger = search;
    [self configSubView];
    if (!STLocationManger.defult.ipx.length) {
        [STLocationManger.defult startUpdatingLocationHande:^(STError *error, CLPlacemark *placemark) {
            [STLocationManger.defult updatePlacemarkWith:placemark];
            if (!error) {
                [self sendNetRequest];
                NSString * area = STLocationManger.defult.lastSubLocality;
                [self.addButton setTitle:area forState:UIControlStateNormal];
                if (!area.length) {
                    [self.addButton setTitle:@"定位失败" forState:UIControlStateNormal];
                }
                //  查询
                NSString * city = STLocationManger.defult.lastCity;
                NSString * name = STLocationManger.defult.lastJieDao;
                self.cityName = city;
                self.currentSarchName = name;
                [self bmp_searchCityName:area subLocation:name];
            }
        }];
    }else{
        NSString * city = STLocationManger.defult.lastCity;
        NSString * name = STLocationManger.defult.lastJieDao;
        self.cityName = city;
        self.currentSarchName = name;
        [self bmp_searchCityName:@"" subLocation:name];
        [self sendNetRequest];
    }
    [self st_setRightItemWithTitle:@"Search" titleColor:OE_LIMITE_COLOR];
    
    [[BMKLocationAuth sharedInstance] checkPermisionWithKey:BAIDU_AK authDelegate:self];
    
    _locationManager = [BMKLocationManager new];
    [self.locationManager setLocatingWithReGeocode:YES];
    _locationManager.delegate = self;
    //设置返回位置的坐标系类型
    _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
    //设置距离过滤参数
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    //设置预期精度参数
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //设置应用位置类型
    _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
    //设置是否自动停止位置更新
    _locationManager.pausesLocationUpdatesAutomatically = NO;
    //设置是否允许后台定位
    //_locationManager.allowsBackgroundLocationUpdates = YES;
    //设置位置获取超时时间
    _locationManager.locationTimeout = 10;
    //设置获取地址信息超时时间
    _locationManager.reGeocodeTimeout = 10;
    [_locationManager startUpdatingLocation];
    // Do any additional setup after loading the view.
}
- (void)setCityName:(NSString *)cityName{
    _cityName = cityName;
    [self.addButton setTitle:cityName forState:UIControlStateNormal];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];

}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_mapView viewWillDisappear];
}
- (void)configMapView{
      [BMKMapManager setCoordinateTypeUsedInBaiduMapSDK: BMK_COORDTYPE_BD09LL];
    
    [self.mapView removeFromSuperview];
    _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, TMUtils.navgationBarBootom + 44, UIScreenWidth, UIScreenHeight * 0.4)];
    _mapView.delegate = self;
    CLLocationCoordinate2D center =  CLLocationCoordinate2DMake(STLocationManger.defult.ipy.floatValue,
                                                                STLocationManger.defult.ipx.floatValue);

    if (self.ipx.length) {
        center =  CLLocationCoordinate2DMake(self.ipy.floatValue,
                                             self.ipx.floatValue);
        
    }
    BMKCoordinateSpan span =  BMKCoordinateSpanMake(5, 5);
    BMKCoordinateRegion regin = BMKCoordinateRegionMake(center, span);
    _mapView.region = regin;
    _mapView.gesturesEnabled = YES;
    _mapView.zoomLevel = 18;
    [_mapView setCenterCoordinate:center animated:YES];
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = BMKUserTrackingModeHeading;
    [self.view addSubview:_mapView];
    
  
}
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    self.tableView.backgroundColor = UIColor.whiteColor;
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, TMUtils.navgationBarBootom, UIScreenWidth, 50)];
    [header st_showTopLine];
    //    [header st_showBottomLine];
    self.addButton = [[STButton alloc] initWithFrame:CGRectMake(15, 0, 200, 44)
                                               title:@"正在定位..."
                                          titleColor:FirstTextColor
                                           titleFont:15
                                        cornerRadius:0
                                     backgroundColor:nil
                                     backgroundImage:nil
                                               image:[UIImage imageNamed:@"22×26地址"]];
    self.addButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    [self.addButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedAddButton];
    }];
    [header addSubview:self.addButton];
    
    
    self.searchTextFied = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth - 30, 34)];
    self.searchTextFied.placeholder = @"please input your address";
    self.searchTextFied.returnKeyType = UIReturnKeySearch;
    self.searchTextFied.backgroundColor = OE_GrayColor;
    self.searchTextFied.layer.cornerRadius = 8;
    self.searchTextFied.font = [UIFont systemFontOfSize:12];
    self.searchTextFied.leftViewMode = UITextFieldViewModeAlways;
    self.searchTextFied.rightViewMode = UITextFieldViewModeAlways;
    STButton * searchButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 34, 34)
                                                        title:@""
                                                   titleColor:SecendTextColor
                                                    titleFont:0
                                                 cornerRadius:0
                                              backgroundColor:nil
                                              backgroundImage:nil
                                                        image:[UIImage imageNamed:@"40×40搜索"]];
    
    self.searchTextFied.rightView = searchButton;
    self.searchTextFied.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 0)];
    
    self.searchTextFied.delegate = self;
    searchButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    
    self.searchTextFied.right = UIScreenWidth - 15;
    self.searchTextFied.centerY = 25;
    [header addSubview:self.searchTextFied];
    
    [self.view addSubview:header];
    
    
    [self configMapView];
    
    
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.frame = CGRectMake(0, _mapView.bottom, UIScreenWidth,TMUtils.tabBarTop - _mapView.bottom + 49);
    
}

#pragma mark --Private Method
- (void)bmp_searchCityName:(NSString*)cityName subLocation:(NSString*)subLocation{
    BMKSuggestionSearchOption* option = [[BMKSuggestionSearchOption alloc] init];
    option.cityname = self.cityName;
    option.keyword  = self.currentSarchName;
    option.cityLimit = YES;
    BOOL flag = [self.searchManger suggestionSearch:option];
    DDLogInfo(@"搜索:%@ %@",option.cityname,option.keyword);
    if (flag) {
        NSLog(@"Sug检索发送成功");
    }  else  {
        NSLog(@"Sug检索发送失败");
    }
}
#pragma mark --BMKMapViewDelegate
- (void)mapView:(BMKMapView *)mapView regionWillChangeAnimated:(BOOL)animated{
    //更新自己的位置
//    CLLocationCoordinate2D center =  CLLocationCoordinate2DMake(STLocationManger.defult.ipy.floatValue,
//                                                                STLocationManger.defult.ipx.floatValue);
//
//    CLLocationCoordinate2D coodinate = center;
//    BMKLocationCoordinateType srctype = BMKLocationCoordinateTypeBMK09LL;
//    BMKLocationCoordinateType destype = BMKLocationCoordinateTypeBMK09MC;
//    CLLocationCoordinate2D cood=[BMKLocationManager BMKLocationCoordinateConvert:coodinate SrcType:srctype DesType:destype];
//
//
//    BMKUserLocation *location = BMKUserLocation.new;
//    CLLocation *mylocation = [[CLLocation alloc] initWithLatitude:cood.latitude longitude:cood.longitude];
//    location.location = mylocation;
//    location.title = STLocationManger.defult.lastJieDao;
//    [_mapView updateLocationData:location];
}
- (void)BMKLocationManager:(BMKLocationManager *)manager didUpdateHeading:(CLHeading *)heading {
    if (!heading) {
        return;
    }
    if (!self.userLocation) {
        self.userLocation = [[BMKUserLocation alloc] init];
    }
    self.userLocation.heading = heading;
    [self.mapView updateLocationData:self.userLocation];
}
- (void)BMKLocationManager:(BMKLocationManager * _Nonnull)manager didUpdateLocation:(BMKLocation * _Nullable)location orError:(NSError * _Nullable)error{
 
    BMKUserLocation * userLocation =  BMKUserLocation.new;
    userLocation.location = location.location;
    
//    BMKCoordinateSpan span =  BMKCoordinateSpanMake(5, 5);
//    BMKCoordinateRegion regin = BMKCoordinateRegionMake(location.location.coordinate, span);
//    _mapView.region = regin;
//    _mapView.zoomLevel = 18;
    [self.mapView updateLocationData:userLocation];
}
#pragma mark --say
- (void)onCheckPermissionState:(BMKLocationAuthErrorCode)iError{
    
}
#pragma mark --BMKSuggestionSearchDelegate
- (void)onGetSuggestionResult:(BMKSuggestionSearch*)searcher result:( BMKSuggestionSearchResult*)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        NSArray * array = result.suggestionList;
        self.dataSouce = NSMutableArray.new;
        if (self.currentSarchName) {
            [self.dataSouce addObject:self.currentSarchName];
        }
        NSArray * namearray  = [array st_arrayFromObjKeyName:@"obj.key"].mutableCopy;
        if (namearray.count) {
            [self.dataSouce addObjectsFromArray:namearray];
        }
        [self.tableView reloadData];
    }
    else {
        NSLog(@"检索失败");
    }
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    cell.textLabel.textColor = UIColorFromRGBA(0x333333);
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    cell.detailTextLabel.textColor = UIColorFromRGBA(0x999999);
    
    NSString *  add = self.dataSouce[indexPath.row];
    cell.textLabel.text = add;
    cell.accessoryType = UITableViewCellAccessoryNone;
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *  add = self.dataSouce[indexPath.row];
    [self sendNetRequesWithAddress:add handle:^(BOOL success, NSString *lat, NSString *lng) {
        if (success) {
            self.ipy = lat;
            self.ipx = lng;
            [self configMapView];
        }
    }];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark --UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        if (textField.text) {
            self.currentSarchName = textField.text;
            [self bmp_searchCityName:@"" subLocation:@""];
            [self.searchTextFied resignFirstResponder];
        }
    }
    return YES;
}

#pragma mark --Action Method
- (void)onSelctedAddButton{
    [self.view endEditing:YES];

}
- (void)st_rightBarAction:(id)sender{
    OEAddressNearViewController * vc = OEAddressNearViewController.new;
    vc.ipx = self.ipx;
    vc.ipy = self.ipy;
    if (!vc.ipx) {
        vc.ipx = STLocationManger.defult.ipx;
        vc.ipy = STLocationManger.defult.ipy;
    }
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark --NetWork Method
- (void)sendNetRequest{
    
}
- (void)sendNetRequesWithAddress:(NSString*)addres handle:(void(^)(BOOL success,NSString * lat,NSString * lng))handle{
    NSMutableDictionary * paramDic = [NSMutableDictionary new];
    NSString *utfAdd = [addres stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString * url = [NSString stringWithFormat:@"http://api.map.baidu.com/geocoder/v2/?address=%@&output=json&ak=%@&callback=showLocation",utfAdd,BAIDU_WEB_AK];
    DDLogInfo(@"url:%@",url);
    DDLogInfo(@"param:%@",paramDic);
    [TMUtils sendNoJsonRequestWithUrl:url params:nil isPost:NO handle:^(BOOL success, NSString *response) {
        
        NSString * jsonStr = response;
        jsonStr  = [jsonStr substringWithRange:NSMakeRange(1, jsonStr.length - 2)];
        NSData * data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        if (jsonStr.length) {
            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            if ([dic.allKeys containsObject:@"result"]) {
                NSString * lat = [dic[@"result"][@"location"][@"lat"] description];
                NSString * lng = [dic[@"result"][@"location"][@"lng"] description];
                if (handle) {
                    handle(success,lat,lng);
                    
                }
                return ;
            }
            
            DDLogInfo(@"%@",dic);
        }
        if (handle) {
            handle(NO,@"",@"");
            
        }
    }];
   
}

@end
